﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using VersionComparer.Base;

namespace VersionComparer.Base
{
    public abstract class WorkerInfoBase : IDisposable
    {
        #region fields
        ManualResetEvent resetEvent = new ManualResetEvent(false);
        bool terminated = false;
        #endregion fields

        #region constructors
        protected WorkerInfoBase(string name, BackgroundWorker worker)
        {
            Name = name;
            Worker = worker;
        }
        #endregion constructors

        #region properties
        public string Name { get; private set; }

        public BackgroundWorker Worker
        {
            get;
            private set;
        }
        #endregion properties

        /// <summary>
        /// Marks the worker as terminated
        /// </summary>
        public void Terminated()
        {
            terminated = true;
            resetEvent.Set();
            
        }
        /// <summary>
        /// Waits for the worker thread
        /// </summary>
        /// <param name="millisecondsToWait">if different from null, the maximum number of milliseconds to wait</param>
        /// <returns>false if if millisecondsToWait is reached, true otherwise</returns>
        public bool Wait(int ?millisecondsToWait)
        {
            if (millisecondsToWait == null)
                millisecondsToWait = -1;
            if (terminated)
                return true;
            resetEvent.WaitOne(millisecondsToWait.Value);
            return terminated;
        }
        public abstract void Execute();

        public void Dispose()
        {
            Dispose(true);
            
            GC.SuppressFinalize(this);
        }
        private void Dispose(bool disposing)
        {
            resetEvent.Dispose();
        }
    }
}
